﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LuaInterface;
using System.IO;

namespace NTUTMessagerServer
{
    public class FriendModel
    {
        public FriendList getFriend(String owner) 
        {
            FriendList friend = new FriendList();
            friend.Load(owner);
            return friend;
        }

        public void addFriend(String owner, String friend) 
        {
            FriendList friends = new FriendList();
            friends.Load(owner);
            friends.Friends.Add(friend);
            friends.Save();

            FriendList friends2 = new FriendList();
            friends2.Load(friend);
            friends2.Friends.Add(owner);
            friends2.Save();
        }

        public void removeFriend(String owner, String friend) 
        {
            FriendList friends = new FriendList();
            friends.Load(owner);
            friends.Friends.Remove(friend);
            friends.Save();

            FriendList friends2 = new FriendList();
            friends.Load(friend);
            friends.Friends.Remove(owner);
            friends.Save();
        }
    }

    public class FriendList 
    {
       public String Owner;
       public List<String> Friends = new List<String>();

       public static string path ="./lua/friend/";

       public void Load(String owner)
       {
           Owner = owner;

           Lua lua = new Lua();

           if (File.Exists(path + owner + ".friend"))
           {

               lua.DoFile(path + owner + ".friend");

               LuaTable table = lua.GetTable("friendList");

               if (table != null)
               {
                   foreach (String s in table.Values)
                   {
                       Friends.Add(s);
                   }
               }
               else
               {
                   return;
               }
           }
           else
           {
               return;
           }
       }

       public void Save()
       {
           StreamWriter sw = new StreamWriter(path + Owner + ".friend", false);
       
            sw.WriteLine("friendList = ");
            sw.WriteLine("{");
                foreach(String s in Friends)
                {
                    sw.WriteLine("\""+s+"\",");
                }
            sw.WriteLine("}");
            sw.Close();
       }
    }

}
